﻿using UnityEngine;
using System.Collections;

public class PlayerPlane :Plane
{
	//修饰符 数据类型  变量名
	private Rigidbody2D rig;
	//飞机的移动速度
	public float speed = 5f;
	//子弹预制体
	public GameObject bulletPrefab;
	//发射子弹的声音片段
	public AudioClip shootSond;
	//声音播放器
	private AudioSource audioSource;
	//发射子弹的频率
	public float shootInterval=0.5f;
	protected override void  Start()
	{
		base.Start ();
		//获取刚体组件
		rig = GetComponent<Rigidbody2D> ();
		InvokeRepeating ("Shoot",0,shootInterval);
		audioSource = gameObject.AddComponent<AudioSource> ();

	}
	void Update()
	{
		//获取用户输入
		float h = Input.GetAxisRaw("Horizontal");
		float v = Input.GetAxisRaw ("Vertical");
		//构造一个移动向量
		Vector2 dir=new Vector2(h,v).normalized;
		//给刚体设置速度
		rig.velocity=dir*speed;

		//限制飞机上下不能超出屏幕
		Vector2 pos=transform.position;//拿到位置
		pos.y = Mathf.Clamp(pos.y,-4.3f,4.5f);//限制
		//左进右出
		if (h<0 && pos.x<-3) {
			pos.x = 3;
		}
		//右进左出
		else if (h>0 && pos.x>3) {
			pos.x = -3;
		}
		transform.position = pos;//使用新的位置
	}

	//发射一颗子弹
	void Shoot()
	{
		Instantiate (bulletPrefab,transform.position,transform.rotation);
		audioSource.PlayOneShot (shootSond);//播放声音
	}
}
